<template>
  <div class="fancy-list" :style="{ height: height + 'px' }" @scroll="onScroll">
    <div class="fancy-list__wrapper">
      <div class="fancy-item" v-for="item in list" :key="item.id">
        <!-- 由父组件来控制，使用 插槽 -->
        <slot :item="item" />
      </div>
    </div>

    <div v-if="!hasMore" class="more">
      <p>别拉了，没有更多了</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, watchEffect } from "vue";
import axios from "axios";

const props = withDefaults(
  defineProps<{
    apiUrl: string;
    page?: number;
    pageSize?: number;
    height: number;
  }>(),
  {
    // 默认值
    page: 1,
    pageSize: 10,
  }
);

const page = ref(props.page);
const pageSize = ref(props.pageSize);
const total = ref(1);
// 是否触底了
const isBottom = ref(false);
// 列表内容
const list = ref<any[]>([]);
// 还有更多
const hasMore = computed(() => list.value.length < total.value);

// 请求数据
const request = async () => {
  const response = await axios.get(props.apiUrl, {
    params: {
      _page: page.value,
      _limit: pageSize.value,
    },
  });
  // response 是包装对象 headers 是响应头 data 是响应体

  // 数据总条数
  const count = response.headers["x-total-count"];
  const resp = response.data;
  list.value = [...list.value, ...resp];
  total.value = +count;
};

// 滚动事件
const onScroll = (event: Event) => {
  const scrollTop = (event.target as HTMLDivElement).scrollTop;
  const clientHeight = (event.target as HTMLDivElement).clientHeight;
  const scrollHeight = (event.target as HTMLDivElement).scrollHeight;

  // TIPS: 50作为一个阈值
  if (scrollTop + clientHeight >= scrollHeight - 50) {
    console.log("触底了");
    isBottom.value = true;
  } else {
    isBottom.value = false;
  }
};

// 监听 isBottom
watch(isBottom, (newValue) => {
  // 触底了，且还有数据
  if (newValue && hasMore.value) {
    page.value++;
    // 重新获取数据
    // request(); // 改成 watchEffect 之后，可以自动重新触发 request 了。
  }
});

watchEffect(request);

// onMounted(() => {
//   request();
// });
</script>

<style scoped>
.fancy-list {
  border: 1px solid #000;
  overflow-y: auto;
}

.fancy-item {
  height: 70px;
  line-height: 70px;
}
</style>
